<template>
  <div class="favorite-container">
    <!-- 收藏列表区域 -->
    <div class="favorite-list-wrapper">
      <table class="favorite-table">
        <thead v-if="favoriteList.length > 0">
          <tr class="table-header">
            <th class="col-img">商品图片</th>
            <th class="col-name">商品名称</th>
            <th class="col-price">商品价格</th>
            <th class="col-action">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr class="table-row" v-for="item in favoriteList" :key="item.id">
            <!-- 商品图片：添加加载失败占位图 -->
            <td class="col-img">
              <div class="img-container">
                <img
                  :src="`http://117.72.153.227/image/${
                    item.fileName || 'default-img.png'
                  }`"
                  alt="商品图片"
                  class="product-img"
                />
              </div>
            </td>
            <td class="col-name">{{ item.productName || "未命名商品" }}</td>
            <td class="col-price">¥{{ item.price }}</td>
            <td class="col-action">
              <button class="btn btn-add-cart" @click="addToCart(item)">
                加入购物车
              </button>
              <!-- 收藏/取消收藏按钮：根据当前商品收藏状态切换 -->
              <button
                class="btn"
                :class="{
                  'btn-cancel-fav': isCurrentFavorited(item.id),
                  'btn-add-fav': !isCurrentFavorited(item.id),
                }"
                @click="toggleFavorite(item.id)"
              >
                {{ isCurrentFavorited(item.id) ? "取消收藏" : "添加收藏" }}
              </button>
            </td>
          </tr>

          <!-- 无收藏商品时显示空状态 -->
          <tr v-if="favoriteList.length === 0" class="empty-row">
            <td colspan="4" class="empty-content">
              <div class="empty-icon">🗂️</div>
              <p class="empty-text">暂无收藏商品</p>
              <button class="btn btn-go-shop" @click="goToHome()">
                去首页逛逛
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "UserFavoriteList",
  data() {
    return {
      favoriteList: [], // 收藏列表
      favoriteStatus: {},
      product: {
        id: 0,
        productName: "",
        description: "",
        price: 0,
        stock: 0,
        fileName: "",
      },
    };
  },

  methods: {
    // 加载收藏列表
    async loadFavoriteList() {
      try {
        const response = await axios.get(
          `/api/product/getFavoriteList`
        );
        this.favoriteList = response.data.list || [];

        // 初始化收藏
        this.favoriteList.forEach((item) => {
          this.$set(this.favoriteStatus, item.id, true);
        });
      } catch (error) {
        console.error("加载收藏列表失败：", error);
        this.$message.error("收藏列表加载失败，请稍后重试");
      }
    },

    // 加入购物车
    async addToCart(product) {
      try {
        const token = sessionStorage.getItem("token");
        if (!token) {
          this.$notify.error("请先登录");
          return;
        }

        const payload = {
          productId: Number(product.id),
          productName: product.productName,
          price: Number(product.price),
          quantity: 1, // 默认数量设为1
          fileName: product.fileName,
          cost: Number(product.price), // 因为数量是1，所以cost等于price
        };

        const response = await axios.post(
          `/api/shoppingCart/addProductToCart`,
          payload,
          {
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
          }
        );

        if (response.data.code === 200) {
          this.$notify.success(`${product.productName} 已添加到购物车`);
        }
      } catch (error) {
        console.error("添加购物车失败:", error);
        this.$notify.error(
          error.response?.data?.message || "添加到购物车失败，请稍后重试"
        );
      }
    },

    // 切换收藏状态
    async toggleFavorite(productId) {
      const isCurrentlyFavorited = this.isCurrentFavorited(productId);

      try {
        if (isCurrentlyFavorited) {
          // 取消收藏
          await axios.delete(
            `/api/product/deleteFavorite/${productId}`
          );
          this.$message.success("取消收藏成功");
          // this.loadFavoriteList();
        }else { 
          // 添加收藏
          await axios.post(
            `/api/product/addFavorite/${productId}`
          );
          this.$message.success("添加收藏成功");
        }
        // 更新收藏状态标记
        this.$set(this.favoriteStatus, productId, !isCurrentlyFavorited);
      } catch (error) {
        this.$message.error(
          `${isCurrentlyFavorited ? "取消" : "添加"}收藏失败，请稍后重试`
        );
      }
    },
    goToHome() {
      this.$router.push("/");
    },
    // 检查当前商品是否已收藏
    isCurrentFavorited(productId) {
      return this.favoriteStatus[productId] || false;
    },
  },

  created() {
    this.loadFavoriteList();
  },
};
</script>

<style scoped>
/* 全局容器：控制页面宽度和居中 */
.favorite-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 16px;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  color: #333;
}

/* 页面标题：上下间距和字体样式 */
.page-header {
  margin-bottom: 28px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.page-header .desc {
  font-size: 14px;
  color: #7f8c8d;
}

/* 列表容器：添加阴影和圆角，提升层次感 */
.favorite-list-wrapper {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 表格样式：宽度100%，边框合并 */
.favorite-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

/* 表格头部：深色背景，加粗文字 */
.table-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.table-header th {
  padding: 16px 20px;
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

/* 表格列宽度分配：响应式调整 */
.col-img {
  width: 120px;
  min-width: 120px;
}

.col-name {
  flex: 1;
  min-width: 200px;
}

.col-price {
  width: 120px;
  min-width: 120px;
}

.col-action {
  width: 220px;
  min-width: 220px;
}

/* 表格行：交替背景色，hover效果 */
.table-row {
  border-bottom: 1px solid #f1f3f5;
  transition: background-color 0.2s ease;
}

.table-row:hover {
  background-color: #fafafa;
}

.table-row td {
  padding: 20px;
  font-size: 14px;
}

/* 商品图片容器：控制大小和圆角 */
.img-container {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* 保持图片比例，填充容器 */
  transition: transform 0.3s ease;
}

.table-row:hover .product-img {
  transform: scale(1.05);
  /* 鼠标悬浮时图片轻微放大 */
}

/* 商品名称：超出部分省略 */
.col-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 价格样式：突出显示 */
.col-price {
  color: #e74c3c;
  font-weight: 500;
}

/* 按钮样式：统一风格，区分功能 */
.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-right: 8px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  /* 图标与文字间距 */
}

/* 加入购物车按钮：绿色系 */
.btn-add-cart {
  background-color: #27ae60;
  color: #fff;
}

.btn-add-cart:hover {
  background-color: #219653;
  box-shadow: 0 2px 4px rgba(39, 174, 96, 0.2);
}

/* 添加收藏按钮：灰色系 */
.btn-add-fav {
  background-color: #f1f3f5;
  color: #495057;
}

.btn-add-fav:hover {
  background-color: #e9ecef;
}

/* 取消收藏按钮：红色系 */
.btn-cancel-fav {
  background-color: #f8d7da;
  color: #e74c3c;
}

.btn-cancel-fav:hover {
  background-color: #f0c6cb;
  box-shadow: 0 2px 4px rgba(231, 76, 60, 0.1);
}

/* 空状态样式：居中显示，友好提示 */
.empty-row td {
  padding: 80px 0;
}

.empty-content {
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: #ced4da;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #6c757d;
  margin-bottom: 24px;
}

/* 去首页按钮：蓝色系 */
.btn-go-shop {
  background-color: #3498db;
  color: #fff;
  padding: 8px 16px;
  font-size: 14px;
}

.btn-go-shop:hover {
  background-color: #2980b9;
  box-shadow: 0 2px 4px rgba(52, 152, 219, 0.2);
}
</style>